
import pandas as pd
import numpy as np
import os
from datetime import datetime
import time
import random
import requests

from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import akshare as ak

  


   
    # print(f"代理是否存活: {proxy_manager.is_proxy_alive(proxy_url)}")


# 获取当前工作目录（可能受运行方式影响）
current_working_dir = os.getcwd()
data_dir = current_working_dir + "/data/"

# for i in range(1, 10):
#     patch_akshare()

def get_unique_files(directory_path, array2):
    """
    读取目录下的所有文件名称，然后从array2中去掉已存在的元素
    
    Args:
        directory_path: 目录路径
        array2: 需要过滤的数组
    
    Returns:
        过滤后的数组
    """
    # 读取目录下的所有文件名称
    try:
        # 获取目录下所有文件和文件夹的名称
        all_items = os.listdir(directory_path)
        
        # 过滤出文件（排除文件夹）
        array1 = [item for item in all_items 
                 if os.path.isfile(os.path.join(directory_path, item))]
        #替換csv文件名
        array3 = [item.replace(".csv","") for item in array1]
        
    except FileNotFoundError:
        print(f"目录 '{directory_path}' 不存在")
        return array2
    except PermissionError:
        print(f"没有权限访问目录 '{directory_path}'")
        return array2
    
    # 从array2中去掉array1中已有的元素
    result = [item for item in array2 if item not in array3]
    
    return result




#获取股指数据
# index_stock_info = ak.index_stock_info()
# index_stock_info.to_csv(os.path.join(data_dir, "index_stock_info.csv"), index=False, encoding="utf_8_sig")
# index_stock_info_pd = pd.DataFrame(index_stock_info)




# # 获取指数列表
# industry_df, concept_df = get_index_list()


index_stock_info = pd.read_csv(os.path.join(data_dir, "index_stock_info.csv"), encoding="utf_8_sig")

index_stock_info_pd = index_stock_info["index_code"]
index_stock_info_pd_unique = get_unique_files(os.path.join(data_dir,"stock_cons"), index_stock_info_pd)
print("获取股指列表数据 saved successfully!")


for stock_info in index_stock_info_pd_unique:
    #日线前复权
    time.sleep(2)
    stock_zh_a_hist_df = ak.index_stock_cons(symbol=stock_info) 
    stock_zh_a_hist_df["symbbol"] = stock_info
    stock_zh_a_hist_df.to_csv(os.path.join(data_dir,"stock_cons","{}.csv".format(stock_info)), index=False, encoding="utf_8_sig")
    prrint("股指成分股获取{}日线前复权数据 saved successfully!".format(stock_info))
print("获取股指成分数据 saved successfully!")
